home *** CD-ROM | disk | FTP | other *** search
- Path: s02.pavilion.co.uk!usenet
- From: AJRobb@pavilion.co.uk (Andy J Robb)
- Newsgroups: comp.lang.c
- Subject: Re: Returning a variable from system() function
- Date: Sun, 21 Jan 1996 06:18:07 GMT
- Organization: Pavilion Internet plc
- Message-ID: <4dslpn$4pf@s02.pavilion.co.uk>
- References: <295336694wnr@iiga.demon.co.uk>
- NNTP-Posting-Host: poolc46.pavilion.co.uk
- X-Newsreader: Forte Free Agent 1.0.82
-
- Pete Ryan <pete@iiga.demon.co.uk> wrote:
-
- >Hiya,
- > I`ve just been experimenting with C on UNIX and have come across a
- >problem!. There is a UNIX command called `find / -name gwire -print`
- >which scans the UNIX drive for files/directories containing `gwire`.
- >Anyway what I want to do is the following...
-
- >#include <stdio.h>
- >#include <stdlib.h>
- >etc
-
- >void main()
- >{
- > char tmp[];
- >
- > chdir("/usr2/willesden");
- >
- > */ offending code below ;( */
- > tmp = system("find . -name gwire");
-
- > printf("%s",tmp");
-
- >}
-
- >Therefore if I run `find . -name gwire -print` it returns all the
- >directories containing `gwire`. However the code above does not
- >work!!. Is it because `= system` returns an integer and not strings???
-
- >Any help would be very much appreciated as I have only just started
- >learning c in the last 2 months.
-
- You have several alternatives:
-
- 1) redirect output from find to a temporary file then read that file.
- This only uses standard functions. The command line is system
- specific though.
-
- #include <stdio.h>
- #include <stdlib.h>
-
- . . .
-
- char line[1024];
- char name[1024];
- FILE *input;
- strcpy(line, "find . -name gwire > "); /* fixed part of command */
- strcpy(name, tmpnam(NULL)); /* get a suitable file name */
- strcat(line, name); /* add it to the end of the command */
- if (system(line)==0) /* do it */
- { input = fopen(name, "r"); /* open the result */
- /* read the file */
- fclose(input); /* close the result */
- }
- else
- { /* handle error */
- }
-
- remove(name); /* clear up */
-
- 2) Use Unix:
- Create a pipe
- fork() a child process.
- In the child:
- - redirect stdout to the pipe
- - exec() the command
- In the parent:
- - read from the pipe until the child terminates (EOF?)
-
- The advantage of the second method is that your program does not have
- to wait for "find" to finish before it can use the results - your
- program is more responsive. If this interests you, read the FAQs in
- comp.unix.programmer.
-
- Regards,
-
- -----BEGIN PGP PUBLIC KEY BLOCK-----
- Version: 2.6.2i
-
- mQCNAy/MpRwAAAEEAOt6uBYqT8yv9EmqNhK8m6v+bYi8QjnGW3Bo6iU1gsMj5pa6
- MHgq99c8deADbE3cbJ6uZS9v5pZE3WCf6HCQjlB5iULA5RZzMdAumd/WUzuL9UT3
- B44D9EqqFIL79FlYb56v4oKFqFp1/J2bIpYUwnUvabGzGjdLrpPl4P16x9sNAAUR
- tCNBbmR5IEogUm9iYiA8QUpSb2JiQHBhdmlsaW9uLmNvLnVrPrQhQW5keSBSb2Ji
- IDxBSlJvYmJAcGF2aWxpb24uY28udWs+
- =/wVD
- -----END PGP PUBLIC KEY BLOCK-----
-
-